import {
  call, put, all, takeLatest, select
} from 'redux-saga/effects';
import {
  GET_MY_COUPON_LIST
} from '@ACTIONS/coupon'
import api from '@API'
import { DEFAULT_TAKE } from '@CONSTANTS/common'
import { getPreMyCouponList } from './dataSelect'

const getMyCouponList = function* getMyCouponList(action) {
  try {
    const { payload: { skip, ...rest } } = action
    const preList = yield select(getPreMyCouponList)
    const realSkip = skip === 0 ? 0 : preList?.length

    const { Coupons } = yield call(api.getMyCouponList, { ...rest, skip: realSkip, take: DEFAULT_TAKE })
    yield put({
      type: GET_MY_COUPON_LIST.SUCCESS,
      data: skip === 0 ? Coupons : [...preList, ...Coupons],
      canLoadMore: Coupons.length >= DEFAULT_TAKE
    })
  } catch (error) {
    yield put({ type: GET_MY_COUPON_LIST.FAILURE, error })
  }
}

export default function* rootSaga() {
  yield all([
    takeLatest(GET_MY_COUPON_LIST.REQUEST, getMyCouponList)
  ])
}
